package com.cctc.rds.raft.core.node;

import java.util.HashMap;
import java.util.Map;

/**
 * 节点投票器 [持有者]。
 */
public class NodeVoterHolder {
    // <任期号，节点投票器>
    private static final Map<Long, NodeVoter> VOTER_MAP = new HashMap<>();
    private long newTerm;

    public synchronized NodeVoter get(long term) {
        this.newTerm = term;
        clear();
        if (!VOTER_MAP.containsKey(term)) {
            VOTER_MAP.put(term, new NodeVoter(term));
        }
        return VOTER_MAP.get(term);
    }

    private void clear() {
        long curTerm = newTerm - 5;
        for (; ; curTerm--) {
            if (VOTER_MAP.remove(curTerm) == null) break;
        }
    }


}
